﻿using System;
using System.ComponentModel;
using CSW.Framework.Common.Binding;
using CSW.Framework.UI.Binding;
using System.Windows.Forms;

namespace CSW.Framework.UI.Binding
{
    /// <summary>
    /// A wrapper class for binding <see cref="ComboBox"/> objects with <see cref="Binder"/>.
    /// </summary>
    public class BindableComboBox<T> : BindableComboBox
    {
        private readonly BindableObject.BaseProperty<BindingList<T>> m_ValueListProperty;

        /// <summary>
        /// Initializes a new instance of the <see cref="BindableComboBox"/> class.
        /// </summary>
        /// <param name="comboBox">The <see cref="ComboBox"/> control to wrap.</param>
        /// <param name="valueListProperty">The value list <see cref="ComplexProperty" />.</param>
        /// <param name="addBlankEntry">if set to <c>true</c>, add a null entry and handle the delete key.</param>
        public BindableComboBox(ComboBox comboBox, BindableObject.BaseProperty<BindingList<T>> valueListProperty, bool addBlankEntry)
            : base(comboBox, valueListProperty.Value ?? new BindingList<T>(), addBlankEntry)
        {
            m_ValueListProperty = valueListProperty;
            m_ValueListProperty.PropertyChanged += m_ValueListProperty_PropertyChanged;
        }

        private void m_ValueListProperty_PropertyChanged(ComplexProperty<BindingList<T>> sender, BindableObject.BaseProperty<BindingList<T>>.PropertyChangedEventArgs e)
        {
            CheckDisposed();

            ValueList = m_ValueListProperty.Value;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            m_ValueListProperty.PropertyChanged -= m_ValueListProperty_PropertyChanged;

            base.Dispose();
        }
    }
}